<template>
  <div class="code-login width-100 m-rem-t-24">
    <el-form ref="loginForm" :model="form" :rules="loginRules" class="form-con">
      <el-form-item prop="mobile">
        <el-input v-model.trim="form.mobile" placeholder="请输入手机号" maxlength="11"
                  @keyup.delete.native="mobileChange"
        >
          <div slot="prefix" class="w-rem-20 h-rem-36 flex row-center col-center">
            <img src="../../../assets/images/businessImages/login/phone.png" alt="" class="w-rem-20 h-rem-20 obj-fit-contain">
          </div>
        </el-input>
      </el-form-item>

      <el-form-item prop="code">
        <el-input v-model.trim="form.code" placeholder="请输入验证码" maxlength="6" class="width-60"
                  @keyup.enter.native="handleLogin"
        >
          <div slot="prefix" class="w-rem-20 h-rem-36 flex row-center col-center">
            <img src="../../../assets/images/businessImages/login/vcode.png" alt="" class="w-rem-20 h-rem-20 obj-fit-contain">
          </div>
        </el-input>
        <el-button class="width-32 m-rem-l-10 m-rem-r-0 p-rem-0 font-rem-12" @click="onCode()">{{
            codeName
          }}
        </el-button>

      </el-form-item>
      <!-- <el-checkbox v-model="save">记住密码</el-checkbox> -->
      <el-button type="primary" class="width-100 m-rem-t-18" @click="handleLogin">登录</el-button>
    </el-form>

    <!-- 选择租户方式 -->
    <tenantMethod ref="tenantMethod" @tenantMethodFun="tenantMethodFun"/>
    <!-- 图片滑动验证 -->
    <Verify
        @success="success"
        mode="pop"
        captchaType="blockPuzzle"
        :imgSize="{ width: '330px', height: '155px' }"
        ref="verify"
    ></Verify>
  </div>
</template>
<script>
import setMessage from '@/utils/publicUtils/message'
import { methodGetApi } from '@/api/publicApi'
// 组件
import tenantMethod from './tenantMethod/index.vue'
import Verify from './verifition/Verify.vue'

export default {
  name: 'Login',
  components: { Verify, tenantMethod },
  inject: {
    login: {
      default: () => ({})
    }
  }, // --> ------ form接值 +选择 弹窗 必加
  provide() {
    return {
      formProvide: this
    }
  },
  data() {
    return {
      save: false,
      form: {
        mobile: '',
        code: ''
        // uuid: ''
      },
      codeName: '获取验证码',
      codeNumber: 60, // 验证码秒数
      codeTime: null,
      loginRules: {
        mobile: [
          { required: false, msg: '手机号', trigger: 'blur', validator: (rule, value, callback) => this.regularFun(rule, value, callback, 'phone') }
        ],

        code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
      }

      //   redirect: undefined,
      //   pcLogoBool: false,
      //   platformName: '',
      //   platformPrefixName: ''
    }
  },
  //   watch: {
  //     $route: {
  //       handler: function(route) {
  //         this.redirect = route.query && route.query.redirect
  //       },
  //       immediate: true
  //     }
  //   },
  mounted() {
  },
  created() {
    // 获取平台信息
    // getPlatform().then((res) => {
    //   this.platformName = res.data.platformName
    //   this.platformPrefixName = res.data.platformPrefixName
    //   const annexPath = res.data.annexPath
    //   localStorage.setItem('platformName', this.platformName)
    //   localStorage.setItem('platformPrefixName', this.platformPrefixName)
    //   localStorage.setItem('logoImg', annexPath)
    // })
    // const loginInfo = localStorage.getItem('login')
    // if (loginInfo != null && loginInfo !== '') {
    //   this.form = JSON.parse(loginInfo)
    //   // this.save = true
    // }
  },
  methods: {

    success(params) {
      // params 返回的二次验证参数, 和登录参数一起回传给登录接口，方便后台进行二次验证
      console.log('abc=====', params)
      const data = {
        mobile: this.form.mobile,
        ...params
      }
      methodGetApi('/sendMessage', data).then(res => {
        console.log(res)
        this.msgAlt('验证码已发送，1分钟内有效', 'success')
        this.codeTime = setInterval(() => {
          if (this.codeNumber <= 0) {
            this.codeNumber = 60
            clearInterval(this.codeTime)
            this.codeName = '获取验证码'
          } else {
            this.codeNumber--
            this.codeName = this.codeNumber + 's'
          }
        }, 1000)
      })
    },

    // 输入框中的
    mobileChange() {
      // this.form.mobile = null
    },

    // 输入框中的
    codeChange() {
      this.form.code = null
    },

    onCode() {
      if (this.codeName == '获取验证码') {
        if (this.form.mobile == '') {
          this.msgAlt(`请填写手机号`, 'error')
        } else if (!(/^1([3-9][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/.test(this.form.mobile))) {
          this.msgAlt(`手机号格式不正确，请重新填写`, 'error')
        } else {
          this.$refs.verify.show()
        }
      } else {
        this.msgAlt(`验证码已发送，请勿重发送`, 'error')
      }
    },

    // 登录
    handleLogin() {
      if (!this.login.loading) {
        // 验证码正确后判断登录名和密码
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            this.getTenantListByUserPhone()
          } else {
            return false
          }
        })
      }
    },

    // 获取 租户
    getTenantListByUserPhone() {
      const data = { phone: this.form.mobile }
      methodGetApi('/tenant/getTenantListByUserPhone', data).then(res => {
        if (res.data.length > 1) {
          this.$refs['tenantMethod'].selectId = null // 赋值 对象数组
          this.$refs['tenantMethod'].dialogListVisibleBool = true
          this.$refs['tenantMethod'].dialogList = res.data
        } else if (res.data.length == 1) {
          // 数据 等于 1  租户id
          localStorage.setItem('tenantId', res.data[0].id)
          this.LoginTo()
        } else {
          this.msgAlt('账号不存在', 'error')
        }
      })
    },

    /**
     * @description: 选择租户回调
     * @author: 张佳敏
     * @param {*} data
     * @return {*}
     */
    tenantMethodFun(data) {
      this.$refs['tenantMethod'].dialogListVisibleBool = false
      this.LoginTo()
    },

    // 登录
    LoginTo() {
      if (!this.login.loading) {
        // 验证码正确后判断登录名和密码
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            this.login.loading = true
            this.$store.dispatch('user/loginSys', this.form).then(() => {
              this.saveLogin() // 保存登录信息
              setMessage()
              // sunbin update 2021/10/15 16:48 防止路劲访问回到之前路径地址
              // this.redirect 历史路径
              // this.$router.push({ path: this.redirect || '/' })
              // this.$router.push({ path: '/' })
              // 时间 ：2022/11/18  张佳敏 修改 跳转地址
              this.$router.push({ path: '/' })
            }).catch(() => {
              this.login.loading = false
            })
          } else {
            return false
          }
        })
      }
    },
    // 保存账户
    saveLogin() {
      if (this.save) {
        const neeForm = {
          username: this.form.username,
          password: this.form.password
        }
        localStorage.setItem('login', JSON.stringify(neeForm))
      } else {
        localStorage.removeItem('login')
      }
    }
  }
}
</script>
<style lang="scss">
.code-login {
  .el-form-item__content {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .el-input__prefix {
    left: 1rem;
  }

  .el-input__inner {
    padding: 0rem 1.2rem 0rem 3.8rem;
    border: 0.1rem solid #D9D9D9;
  }
}
</style>
